package com.hopu.v1.service.admin.subject.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopu.v1.exception.BusinessException;
import com.hopu.v1.mapper.admin.subject.SubjectMapper;
import com.hopu.v1.pojo.common.PageData;
import com.hopu.v1.pojo.subject.Subject;
import com.hopu.v1.service.admin.subject.SubjectService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject>
        implements SubjectService {
    
    @Resource
    private SubjectMapper subjectMapper;


    @Override
    public PageData<Subject> selectAll(Integer currentPage, Integer pageSize) {
        List<Subject> subjects = subjectMapper.selectAll((currentPage-1)*pageSize, pageSize);
        Integer total = subjectMapper.selectAllCount();
        return new PageData<>(currentPage,pageSize,total,subjects);
    }

    @Override
    public void add(Subject subject) {
        // 检查学科名称是否已存在
        LambdaQueryWrapper<Subject> wrapper = new LambdaQueryWrapper<Subject>()
                .eq(Subject::getSubjectName, subject.getSubjectName());
        Subject existingSubject = getOne(wrapper);
        if (existingSubject!= null) {
            throw new BusinessException("该学科名称已存在，请更换其他名称");
        }
        save(subject);
    }

    @Override
    public void update(Subject subject) {
        // 先获取要更新的学科原来的名称
        Subject originalSubject = getById(subject.getId());
        if (originalSubject == null) {
            throw new BusinessException("找不到要更新的学科记录");
        }

        // 检查新的学科名称是否已存在于其他记录中（排除当前正在更新的记录）
        LambdaQueryWrapper<Subject> wrapper = Wrappers.<Subject>lambdaQuery()
                .eq(Subject::getSubjectName, subject.getSubjectName())
                .ne(Subject::getId, subject.getId());
        Subject existingSubject = getOne(wrapper);

        if (existingSubject!= null) {
            throw new BusinessException("该学科名称已存在，请更换其他名称");
        }

        updateById(subject);
    }
    
    @Override
    public void updateStatus(Subject subject) {
        if (subject.getId() == null) {
            throw new BusinessException("ID不能为空");
        }
        baseMapper.updateById(subject);
    }
    
    @Override
    public List<Subject> getSubjectByName(String subjectName) {
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("subject_name", subjectName);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<Subject> getSubjectByStaffId(Integer empId) {
        return subjectMapper.getSubjectByStaffId(empId);
    }

}




